package kr.co.hk.board.control;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.hk.board.dto.BoardDTO;

/**
 * 
 * 
 * Servlet implementation class BoardControl
 */
public class BoardControl extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public BoardControl() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request,response);
	}

	public void doProcess(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("euc-kr");
		 response.setContentType("text/html; charset=euc-kr");
		 
		 Command cmd = new Command(request);
		 BoardDAO dao = new BoardDAO();
		 
		 if(cmd.getCmd().equalsIgnoreCase("blist")){
			 ArrayList<BoardDTO> list = dao.getAllBoards();
			 request.setAttribute("blist", list);
			 dispatcher("./boardlist.jsp", request, response);
		 
		 }else if (cmd.getCmd().equalsIgnoreCase("addboard")) {
			String id = request.getParameter("id");
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			
			BoardDTO dto = new BoardDTO();
			dto.setUserid(id);
			dto.setTitle(title);
			dto.setContent(content);
			
			dao.insertBoard(dto);
			
			dispatcher("./boardcontrol?command=blist", request, response);
			 
		}
	}
	
	public void dispatcher(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
}
